##########################################################################################

library(data.table)
library(optparse)
library(dplyr)
library(RColorBrewer)
library(ggpubr)
library(ggsci)

##########################################################################################

option_list <- list(
    make_option(c("--ccf_file"), type = "character") ,
    make_option(c("--type"), type = "character") ,
    make_option(c("--gene_list"), type = "character") ,
    make_option(c("--sample_info"), type = "character") ,
    make_option(c("--gtf_file"), type = "character") ,
    make_option(c("--rsem_file"), type = "character") ,
    make_option(c("--out_path"), type = "character")
)

if(1!=1){
    
    ccf_file <- "~/20220915_gastric_multiple/dna_combinePublic/mutationTime/result/All_CCF_mutTime.addShare.tsv"
    sample_info <- "~/20220915_gastric_multiple/dna_combinePublic/config/tumor_normal.class.list"
    gene_list <- "~/20220915_gastric_multiple/dna_combinePublic/mutsig_check/smg.list"
    out_path <- "~/20220915_gastric_multiple/dna_combinePublic/images/GeneLOH"
    type <- "IGC"
    rsem_file <- "~/20220915_gastric_multiple/dna_combinePublic/mRNA/CombineTMM.DNAUse.MergeMutiSample.tsv"
    gtf_file <- "~/ref/GTF/gencode.v19.ensg_genename.txt"

}

###########################################################################################

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

gene_list <- opt$gene_list
sample_info <- opt$sample_info
out_path <- opt$out_path
ccf_file <- opt$ccf_file
type <- opt$type
gtf_file <- opt$gtf_file
rsem_file <- opt$rsem_file

###########################################################################################

dir.create(out_path , recursive = T)
col <- c( "#006699","#DDA520"  )

###########################################################################################

dat_info <- data.frame(fread(sample_info))
dat_gene <- data.frame(fread(gene_list))
dat_ccf <- data.frame(fread(ccf_file))
dat_expression <- data.frame(fread(rsem_file))
dat_gtf <- data.frame(fread(gtf_file , header = F))

colnames(dat_gtf) <- c("gene_id" , "Hugo_Symbol")

###########################################################################################

Variant_Type <- c("Missense_Mutation","Nonsense_Mutation","Frame_Shift_Ins","Frame_Shift_Del","In_Frame_Ins","In_Frame_Del","Splice_Site","Nonstop_Mutation")

###########################################################################################
## 关注的病理亚型
if(type == "IGC"){
    dat_info <- subset( dat_info , Type == "IM + IGC" & Type != "IM + IGC + DGC" )
}else if(type == "DGC"){
    dat_info <- subset( dat_info , Type == "IM + DGC" & Type != "IM + IGC + DGC")
}else if(type == "All"){
    dat_info <- subset( dat_info , Type != "IM + IGC + DGC" )
    #dat_info <- dat_info
}

dat_ccf <- subset( dat_ccf , ID %in% dat_info$ID )

###########################################################################################

dat_expression <- merge( dat_expression , dat_gtf , by = "gene_id" )


###########################################################################################
## 判断基因多少比例出现在Trunk、Pre_Private、Inv_Private
result_plot <- c()
gene_list <- dat_gene$Gene_Symbol

for( geneN in gene_list ){

    tmp <- subset( dat_ccf , Variant_Classification %in% Variant_Type & Hugo_Symbol == geneN )
    tmp_expression <- subset( dat_expression , Hugo_Symbol == geneN )
    tmp_expression <- tmp_expression[ , !(colnames(tmp_expression) %in% c("Hugo_Symbol" , "gene_id")) ]
    tmp_expression <- data.frame(sample_class = colnames(tmp_expression) , TMM = as.numeric(tmp_expression))
    tmp_expression$Class <- sapply(strsplit( tmp_expression$sample_class , "_" ) , "[" , 2 )
    tmp_expression$ID <- sapply(strsplit( tmp_expression$sample_class , "_" ) , "[" , 1 )

    if(nrow(tmp) > 0 & nrow(subset( dat_expression , Hugo_Symbol == geneN )) > 0 ){
        tmp$LOH <- ifelse( tmp$minor_cn == 0 & tmp$total_cn == 2 , "LOH" , "Non-LOH" )
        #tmp <- subset( tmp , Class != "IM" )

        res_tmp <- c()
        for( sample in unique(tmp$ID) ) {
            tmp_use <- subset( tmp , ID == sample )
            tmp_use <- unique(tmp_use[,c("ID" , "CLS" , "LOH" , "Class")])

            ## 一个人若发生多个突变，算最早的
            if( length(which(tmp_use$CLS=="clonal [share]")) > 0 ){
                tmp_use <- subset( tmp_use , CLS == "clonal [share]" )
            }else if( length(which(tmp_use$CLS=="clonal [early]")) > 0 ){
                tmp_use <- subset( tmp_use , CLS == "clonal [early]" )
            }else if( length(which(tmp_use$CLS=="clonal [NA]")) > 0 ){
                tmp_use <- subset( tmp_use , CLS == "clonal [NA]" )
            }else if( length(which(tmp_use$CLS=="clonal [late]")) > 0 ){
                tmp_use <- subset( tmp_use , CLS == "clonal [late]" )
            }else if( length(which(tmp_use$CLS=="subclonal")) > 0 ){
                tmp_use <- subset( tmp_use , CLS == "subclonal" )
            }
            res_tmp <- rbind(res_tmp , tmp_use)
        }

        ## 突变型中的表达
        res_tmp$sample_class <- paste0( res_tmp$ID , "_" , res_tmp$Class )
        res_tmp_mut <- merge( res_tmp , tmp_expression[,c("sample_class" , "TMM")] )
        res_tmp_mut$CLS_new <- ifelse( res_tmp_mut$CLS %in% c("clonal [early]" , "clonal [share]") , "Share/Early" , "Non-Share/Early" )

        ## 野生型中的表达
        res_tmp_wild <- subset( tmp_expression , !(sample_class %in% res_tmp$sample_class) & ID %in% dat_info$ID & Class != "Normal" )
        res_tmp_wild$CLS_new <- "Wild"

        ## 合并
        res_plot <- rbind( res_tmp_mut[,c( "ID" , "Class" , "CLS_new" , "TMM")] , res_tmp_wild[,c( "ID" , "Class" , "CLS_new" , "TMM")] )
        res_plot$Hugo_Symbol <- geneN

        result_plot <- rbind(result_plot , res_plot)
    }
}

out_name <- paste0(out_path , "/Driver.",type,".Expression.tsv")
write.table( result_plot , out_name , row.names = F , sep = "\t" , quote = F )

###########################################################################################

plotTpm <- function(tmp_dat = tmp_dat , out_name = out_name , title = title){

    my_comparisons_1 <- list( 
        c(1, 2), c(1, 3) , 
        c(2, 3) )

    plot <- ggplot( tmp_dat , aes( x = CLS_new , y = TMM , color = CLS_new ) ) +
        geom_boxplot(alpha =1 , outlier.size=0 , size = 0.9 , width = 0.6) +
        geom_jitter(position = position_jitter(0.17) , size = 1 , alpha = 0.7) +
        facet_grid(.~Class,space='free_x',scales='free_x') +
        scale_fill_npg()+
        scale_color_npg()+
        xlab(NULL) +
        ylab("TMM")+
        theme_bw() +
        ggtitle(title) +
        stat_compare_means(comparisons = my_comparisons_1) +
        theme(panel.background = element_blank(),#设置背影为白色#清除网格线
            legend.position ='none',
            legend.title = element_blank() ,
            panel.grid.major=element_line(colour=NA),
            plot.title = element_text(size = 8,color="black",face='bold'),
            legend.text = element_text(size = 10,color="black",face='bold'),
            axis.text.y = element_text(size = 10,color="black",face='bold'),
            axis.title.x = element_text(size = 10,color="black",face='bold'),
            axis.title.y = element_text(size = 10,color="black",face='bold'),
            axis.ticks.x = element_blank(),
            axis.text.x = element_text(size = 8,color="black",face='bold',angle = 45, vjust = 1, hjust=1) ,
            axis.line = element_line(size = 0.5)) 
    ggsave(file=out_name,plot=plot,width=5,height=5)

}

result_plot$CLS_new <- factor( result_plot$CLS_new , levels = c("Share/Early" , "Non-Share/Early" , "Wild") )
for( geneN in unique(result_plot$Hugo_Symbol) ){
    tmp_dat <- subset( result_plot , Hugo_Symbol == geneN )

    if(nrow( tmp_dat ))

    title <- paste0(
        "Gene : " , geneN , "\n" 
    )

    print(geneN)

    out_name <- paste0(out_path , "/Driver.",type,".Expression.",geneN,".pdf")
    plotTpm(tmp_dat = tmp_dat , out_name = out_name , title = title)

}